// components/product-brokage-item/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { formatDecimal, formatInputDecimal } from '../../../common/utils';
import { tipToast } from '../../../common/env';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        maxPercent: {
            type: Number,
            value: 0,
        },
        bonusInfo: {
            type: Object,
            value: {},
        },
        productInfo: {
            type: Object,
            value: {},
        },
        canModify: {
            type: Boolean,
            value: true,
        },
    },
    observers: {
        'bonusInfo, productInfo': function (bonusInfo, productInfo) {
            if (bonusInfo && productInfo) {
                let { bonusRate } = bonusInfo;
                if (bonusRate) bonusRate = bonusRate / 10;
                const { priceMin, priceMax } = productInfo;
                const hasSkus = priceMin != priceMax;
                const priceStr = `¥ ${priceMin ? priceMin / 100 : priceMin}${hasSkus ? '-' + (priceMax ? priceMax / 100 : priceMax) : ''}`;
                const bonusStr = `¥ ${formatDecimal((priceMin ? priceMin / 100 : priceMin) * bonusRate / 100)}${hasSkus ? '-' + formatDecimal(((priceMax ? priceMax / 100 : priceMax)) * bonusRate / 100) : ''}`;
                this.setData({ priceStr, bonusStr, bonusRate });
            }
        },
    },
    data: {
        priceStr: '',
        bonusStr: '',
        bonusRate: '',
    },
    methods: {
        handleChange(e) {
            if (!this.data.canModify) {
                return;
            }

            const maxPercent  = this.data.maxPercent;
            const { productId } = this.data.bonusInfo;
            let bonusRate = formatInputDecimal(e.detail.value, 1);
            if (bonusRate < 0) {
                tipToast('请输入正确的分账比例');
                return;
            }
            if (bonusRate > maxPercent) {
                tipToast(`分账比例最高不超过${maxPercent}%`);
                bonusRate = '';
            }
            if (bonusRate) bonusRate = bonusRate * 10;
            this.triggerEvent('change', {
                productId,
                bonusRate,
            });
        },
    }
})
